/*** ^^A -*-C++-*- **********************************************/
/*      seq_sl - set up sequential spinlock exp-ts   28.05.2020 */
/****************************************************************/
/*      Short Description :                                     */
/*      AU program to set up shape list for sequential exp-ts   */
/****************************************************************/
/*      Keywords :                                              */
/*      shapelist, peaklist                                      */
/****************************************************************/
/*      Description/Usage : seq_sl expno                        */
/*      reads peaklist from: expno/pdata/1/peaklist.xml and     */
/*      create a shape list in current exp-t                    */
/*      based on WaveMaker (wvm)                                */
/*      will set 1 TD to the nearest power of 2                 */
/*      and increase the dimensionality from 1D to 2D           */
/*      works only with spinock (cw) shapes                     */
/*      must use userA1 e.g. :                                  */
/*             sp55(p55):wvm:xxx:f1 cw_i(100 ms; B1max=100 Hz)  */
/*      The VPLIST parameter may contain variable duration list */
/*      if the VP list is not set a constant duration as        */
/*      specified in userA1 is used. The B1 field multipliers   */
/*      are stored in lists/va directory with the same name as  */
/*      the shape list except with the .va extension. If the    */
/*      .va file is missing a constant amplitude sspinlocks are */
/*      used. Note that VALIST parameter is set to the shape    */
/*      list with extension .sp and the .va multiplier list     */
/*      remains invisible to the user                           */
/****************************************************************/
/*      Author(s) :                                             */
/*      Name            : Eriks Kupce                           */
/*      Organisation    : Bruker BioSpin                        */
/*      Email           : eriks.kupce@bruker.com                */
/****************************************************************/
/*      Name            Date    Modification:                   */
/*      eku             280520  created                         */
/****************************************************************/


FILE *src, *trg;
char sourcefile[PATH_MAX], targetfile[PATH_MAX], shname[PATH_MAX], fname[PATH_MAX];
char *ch, xstr[256], str2[256], spx[8], px[8];
int  i, j, numpeaks, td = 1;
int  parmode, ret, sexpno = 1;
double a1 = 0, a2 = 0, a3 = 0, pbw=-0.1, sfrq=0.1, o1hz=0.0; 
float spw=0.0, pw=0.0;

FETCHPAR("PARMODE", &parmode)

if (parmode > 1)
{
  Proc_err(DEF_ERR_OPT, "Program only applicable to 1D and 2D data");
  ABORT
}
else if (parmode < 1  &&  access(ACQUPATH("fid"), F_OK) == 0)
{
  Proc_err(DEF_ERR_OPT, "Program not applicable to 1D raw data");
  ABORT
}

FETCHPAR("USERA1", xstr) 
if(strstr(xstr,":wvm:")==NULL)
{
  Proc_err(DEF_ERR_OPT, "WaveMaker command is missing in userA1");
  ABORT
}

if(strstr(xstr,":f1") !=NULL)  // (offset[i1] + o1) / sfo1);
{
  FETCHPAR("SFO1", &sfrq) 
  FETCHPAR("O1", &o1hz) 
}
else if(strstr(xstr,":f2") !=NULL)
{
  FETCHPAR("SFO2", &sfrq) 
  FETCHPAR("O2", &o1hz) 
}
else if(strstr(xstr,":f3") !=NULL)
{
  FETCHPAR("SFO3", &sfrq) 
  FETCHPAR("O3", &o1hz) 
}

XCMD("wvm -a");
if((ch=strstr(xstr,"sp"))!=NULL) 
  sscanf(ch+2, "%d", &j);
strcpy(xstr, ch+2);
sprintf(spx, "SPW %d", j);
sprintf(str2, "SPNAM %d", j);
if(((ch=strchr(xstr,'p'))!=NULL) && (isdigit((int) *(ch+1))))
	 sscanf(ch+1, "%d", &j);	
strcpy(xstr, ch+2);
sprintf(px, "P %d", j);
FETCHPAR(spx, &spw)
FETCHPAR(px, &pw)
FETCHPAR(str2, shname);

ch=strchr(xstr,'(');
if(ch != NULL) 
{
  j=sscanf(ch+1, "%s %s", fname, str2); 
  if(j==2)
  {
    if((str2[0] == 'm') || (str2[0] == 's') || (str2[0] == 'u'))     
      i=0;
    else
    {
      Proc_err(DEF_ERR_OPT, "incorrect time units in userA1 wvm statement: %s", str2);
      ABORT
    }
  }
  else
    fname[0]='\0';
}


if (i_argc > 2)
  sexpno = atoi(i_argv[2]);
else
  GETINT("Enter peaklist EXPNO:", sexpno)

numpeaks=0;  
numpeaks = readPeakList(VARPROCPATH(name, sexpno, 1, "peaklist.xml"));

if(numpeaks < 1)
{
  Proc_err(DEF_ERR_OPT, "the peaklist appears to be empty: \n %s", sexpno);
  ABORT
}

double ofs[numpeaks], pwx[numpeaks];

for(i=0; i<numpeaks; i++) 
{
  a1 = getPeakFreqHz(i);
  ofs[i] = a1-o1hz;
}
freePeakList();

strcpy(xstr, shname);
ch=strstr(xstr, ".wv");
if(ch!=NULL) *ch='\0';
strcat(xstr,".vp");

FETCHPAR("VPLIST", str2);  // check the number of pulses in vp list 
if((strlen(xstr) > 0) && (strcmp(xstr, str2) == 0))
{
  if(getParfileDirForRead(str2, "VP_DIRS", fname) < 0)
  {
    Proc_err(DEF_ERR_OPT, "Failed to find VPLIST directory for read.");
    ABORT
  }

  if((src=fopen(fname, "r"))!=NULL)
  {
	  i=0;
    while(fgets(xstr, sizeof(xstr), src)) 
    {
  	  if(sscanf(xstr, "%lf", &a1) == 1)
        i++;
    }
  
    if(i!=numpeaks)
    {
      Proc_err(DEF_ERR_OPT, "Number of peaks in peaklist (%d) and pulse list (%d) differs", numpeaks, i);
      ABORT
    }
  }
}

strcpy(str2, shname);
ch=strstr(str2, ".wv");
if(ch!=NULL) *ch='\0';
strcat(str2,".va");

if(getParfileDirForRead(str2, "VA_DIRS", fname) < 0)
{
  Proc_err(DEF_ERR_OPT, "Failed to find VALIST directory for read.");
  ABORT
}

if((src=fopen(fname, "r"))!=NULL)
{
	i=0;
  while(fgets(xstr, sizeof(xstr), src)) 
  {
  	if(sscanf(xstr, "%lf", &a1) == 1)
      i++;
  }
  
  if(i!=numpeaks)
  {
    Proc_err(DEF_ERR_OPT, "Number of peaks in peaklist and %s differs", str2);
    ABORT
  }
  
  i=0;
  fseek(src, 0, 0);
  while(fgets(xstr, sizeof(xstr), src)) 
  {
  	if(sscanf(xstr, "%lf", &a1) == 1)
      pwx[i++] = spw*a1*a1; 
  }
}
else
{
  for(i=0; i<numpeaks; i++) 
    pwx[i]=spw;
}

strcpy(xstr, shname);
ch=strstr(xstr, ".wv");
if(ch!=NULL) *ch='\0';

sprintf(str2, "%s.sp", xstr);
if(getParfileDirForWrite(str2, "SP_DIRS", fname) < 0)
{
  Proc_err(DEF_ERR_OPT, "Failed to find shapelist directory for write.");
  ABORT
}

if((trg=fopen(fname, "w"))==NULL)
{
  Proc_err(DEF_ERR_OPT, "Failed to open shapelist file for write: \n %s", fname);
  ABORT
}

for(i=0; i< numpeaks; i++)
  fprintf(trg, "%5.4e W %10.2f 0.0 %s\n", pwx[i], ofs[i], shname);

fclose(trg);  

STOREPAR("VALIST", str2);

// write file for 2D reconstruction 

strcpy(fname, ACQUPATH("ht.pkl"));
if((trg=fopen(fname, "w"))==NULL)
{
  Proc_err(DEF_ERR_OPT, "Failed to open file for write: \n %s", fname);
  ABORT
}
fprintf(trg, "# Frequency list for 2D reconstruction\n"); 
fprintf(trg, "# pulprog= ht_inv\n");
fprintf(trg, "%4d %2d %6.2f\n", numpeaks, 0, 25.0);
for(i=0; i<numpeaks; i++)
  fprintf(trg, "%12.2f\n", ofs[i]);
fclose(trg);


// ---------- TD adjustments --------
  	  	
while (td < numpeaks)
  td *= 2;

if (parmode < 1)
{                       
  XCMD("chparmod A2")
  XCMD("chparmod P2")
}

STOREPAR1("TD", td)
STOREPAR1("FnMODE", 1)

FETCHPAR("TD", &td)

if (td > 4096)
{
  char tdtxt[256], ktxt[256];

  ktxt[0] = 0;
  sprintf(tdtxt, "%d", td);
  GETSTRING("Enter TD{F2} for the 2D experiment:", tdtxt)

  if (sscanf(tdtxt, "%d%s", &td, ktxt) > 0  &&  td > 0)
  {
    if (ktxt[0] == 'k'  ||  ktxt[0] == 'K')
      td *= 1024;

    STOREPAR("TD", td)
  }
}

QUIT
